(function($) {
    var officeFilter = "All";
    $.fn.roomcolumnFilters = function(settings) {
        var defaults = {
            wildCard: "*",
            notCharacter: "!",
            caseSensitive: false,
            minSearchCharacters: 1,
            excludeColumns: [],
            alternateRowClassNames: [],
            underline: false
        };
        settings = $.extend(defaults, settings);

        return this.each(function() {

            function regexEscape(txt, omit) {
                var specials = ['/', '.', '*', '+', '?', '|',
								'(', ')', '[', ']', '{', '}', '\\'];

                if (omit) {
                    for (var i = 0; i < specials.length; i++) {
                        if (specials[i] === omit) { specials.splice(i, 1); }
                    }
                }

                var escapePatt = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
                return txt.replace(escapePatt, '\\$1');
            }

            var obj = $(this),
				filterRoomRow = document.createElement('tr'),
				wildCardPatt = new RegExp(regexEscape(settings.wildCard || ''), 'g'),
				filter;

            function addClassToColumn(iColNum, sClassName) {
                $('tbody:first tr', obj).each(
					function() {
					    $('td', this).each(
							function(iCellCount) {
							    if (iCellCount === iColNum) {
							        $(this).addClass(sClassName);
							    }
							});
					}
				);
            }
            function genAlternateClassNames() {
                if (settings.alternateRowClassNames && settings.alternateRowClassNames.length) {
                    var sFirst = settings.alternateRowClassNames[0] || '',
						sSecound = settings.alternateRowClassNames[1] || '',
						bOddRow = true;

                    $('tbody:first tr', obj).each(
						function() {
						    if ($(this).css('display') !== 'none') {
						        $(this).removeClass(sFirst).removeClass(sSecound);
						        $(this).addClass((bOddRow) ? sFirst : sSecound);
						        bOddRow = !bOddRow;
						    }
						}
					);
                }
            }

            $('tbody:first tr:first td', obj).each(
				function(iColCount) {
				    //create a select list for each filter column
				    var filterRoomColumn = document.createElement('td');
				    var i = 0;
				    var $roomSelect = $('<select class="selectfilter"></select>');
				    var $this = $(this);
				    var colindex = $this.parent().children().index($this) + 1;
				    var roomdictionary = [];
				    $("table#tblRoomDetails tr td:nth-child(" + colindex + ")").each(function() {
				        var text = $(this).text();
				        roomdictionary[text] = true;
				    });
				    var roomcolkeys = [];
				    for (i in roomdictionary) roomcolkeys.push(i);
				    //colkeys.sort();
				    $roomSelect.append('<option value="All">All</option>');
				    for (i = 0; i < roomcolkeys.length; i++) {
				        if (roomcolkeys[i] === "indexOf") continue; //weird stuff happens in ie and chrome, firefox is awesome
				        if ($.trim(roomcolkeys[i]).length > 0)
				            $roomSelect.append('<option value="' + roomcolkeys[i] + '">' + roomcolkeys[i] + '</option>');
				    }
				    $roomSelect.change(function() {
				        //create an array of the filters selected values
				        var colIndexes = [];
				        var selectedOptions = [];
				        $("#tblRoomDetails").find(".selectfilter").each(function() {
				            $this = $(this);
				            var $parent = $(this).parent();
				            colIndexes.push($parent.parent().children().index($parent) + 1);
				            selectedOptions.push($this.children(":selected").text());
				        });

				        //show or hide the corresponding rows
				        $("#tblRoomDetails").find("tr").each(function(rowindex) {
				            if (rowindex > 0) {
				                var rowok = true;
				                for (i = 0; i < colIndexes.length; i++) {
				                    text = $(this).find("td:nth-child(" + colIndexes[i] + ")").text();
				                    if (selectedOptions[i] != "All" && text != selectedOptions[i]) rowok = false;
				                }
				                if (rowok === true) {
				                    if ($(this)[0].id != "noresults")
				                        $(this).show();
				                }
				                else {
				                    if (rowindex != 1)
				                        $(this).hide();
				                }
				            }
				        });

				    });

				    $(filterRoomColumn).append($roomSelect);
				    $(filterRoomRow).append(filterRoomColumn);

				    if (settings.excludeColumns && settings.excludeColumns.length) {
				        for (var i = 0; i < settings.excludeColumns.length; i++) {
				            if (settings.excludeColumns[i] === iColCount) {
				                //$aClearFilter.css('display', 'none');
				                //$select.css('display', 'none');
				                //$roomSelect.css('display', 'none');
				            }
				            $roomSelect.css('display', 'none');
				        }
				    }
				    //$roomSelect.css('display', 'none');
				    addClassToColumn(iColCount, '_filterCol' + iColCount);
				}
			);

            $(filterRoomRow).addClass('filterColumns');
            $('thead:first', obj).append(filterRoomRow);
            $(filterRoomRow).hide();
            genAlternateClassNames();
            settings.notCharacter = regexEscape(settings.notCharacter || '');

            //*** Cell click ***
            $(".roomfilter").click(function() {
                 $(".clearRoomFilter").attr({ 
                    src:"images/clear_filter.jpg"
                });
                var colindex;
                if ($(this)[0].nodeName == "A") //if child element is Anchor tag
                    colIndex = $(this)[0].parentNode.cellIndex;
                else
                    colIndex = $(this)[0].cellIndex;

                if (colIndex == 2) {
                    $(".clearRoomFilter:eq(0)").css("visibility", "visible");
                    if ($(this)[0].nodeName == "A") {
                        $(this).hide();
                        officeFilter = "All";
                    }
                    else {
                        //show clear filter
                        var cellValue = $(this)[0].innerText;
                        if (cellValue != undefined)
                            officeFilter = $(this)[0].innerText;
                        else
                            officeFilter = $(this).text();
                    }
                }

                //create an array of the filters selected values
                var colIndexes = [];
                var selectedOptions = [];

                $("#tblRoomDetails").find(".selectfilter").each(function() {
                    $this = $(this);
                    var $parent = $(this).parent();
                    colIndexes.push($parent.parent().children().index($parent) + 1);
                    $("#tblRoomDetails").find(".selectfilter:eq(2)").children(":selected").text(officeFilter);
                    selectedOptions.push($this.children(":selected").text());
                });

                //show or hide the corresponding rows
                $("#tblRoomDetails").find("tr").each(function(rowindex) {
                    if (rowindex > 0) {
                        var rowok = true;
                        for (i = 0; i < colIndexes.length; i++) {
                            text = $(this).find("td:nth-child(" + colIndexes[i] + ")").text();
                            if (selectedOptions[i] != "All" && text != selectedOptions[i]) rowok = false;
                        }
                        if (rowok === true) {
                            if ($(this)[0].id != "noresults")
                                $(this).show();
                        }
                        else {
                            if (rowindex != 1)
                                $(this).hide();
                        }
                    }
                });
                if (officeFilter == "All") {
                    $(".filterColumns").css("display", "none");
                }
                $(".clearRoomFilter").click(function() {
                    officeFilter = "All";
                    $("#tblRoomDetails").find("tr").show();
                    $(".filterColumns").css("display", "none");
                    $(".clearRoomFilter").css("visibility", "hidden");
                });
            }); // Close Clear  Filter
        });
    }
})(jQuery);